<template>
    <el-tooltip effect="dark" placement="top" :enterable="true" :disabled="!showTooltip">
        <template slot="content">
            <div class="table-custom-tooltip">{{ contentText }}</div>
        </template>
        <div class="text-overflow" ref="cell">
            <slot v-if="$slots.default"></slot>
            <template v-else>{{ content }}</template>
        </div>
    </el-tooltip>
</template>

<script>
export default {
    name: 'CustomTooltip',
    props: {
        content: String
    },
    data() {
        return {
            showTooltip: false,
            contentText: ''
        }
    },
    watch: {
      content: {
        handler(){
            this.handleContent()
        },

        immediate: true
      }
    },
    methods: {
        handleContent() {
          this.$nextTick(()=> {

            const cellChild = this.$refs.cell
            if (!cellChild.childNodes.length) {
              this.showTooltip = false
              this.contentText = this.content
              return
            }
            // use range width instead of scrollWidth to determine whether the text is overflowing
            // to address a potential FireFox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1074543#c3
            const range = document.createRange()
            range.setStart(cellChild, 0)
            range.setEnd(cellChild, cellChild.childNodes.length)

            const rangeWidth = range.getBoundingClientRect().width
            const padding = 20
            this.contentText = [...cellChild.childNodes].map((item) => item.innerText || item.textContent).join(' ')
            this.showTooltip = rangeWidth + padding > cellChild.parentNode.offsetWidth
          })

        }
    }
}
</script>
<style lang="scss" scoped>
.text-overflow {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>
<style>
.table-custom-tooltip {
    max-width: 600px !important;
    line-height: 20px;
    font-size: 14px;
}
</style>
